package org.zt.ccty.springboot_mybatis_demo.config.mongodb;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
@Component
public class MongoDBConnFactory {

	private  MongoClient mongoClient = null;
	@Value("${mongodb.host}")
	private  String HOST;
	@Value("${mongodb.port}")
	private  int PORT;
	@Value("${mongodb.username}")
	private  String USERNAME;
	@Value("${mongodb.password}")
	private  String PASSWORD;
	@Value("${mongodb.dbname}")
	private  String DBNAME;
	@Value("${mongodb.connectionsperhost}")
	private  int CONNECTIONS_PER_HOST;
	@Value("${mongodb.threadsallowedtoblockforconnectionmultiplier}")
	private  int THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER;
	@Value("${mongodb.maxwaittime}")
	private  int MAX_WAIT_TIME;
	@Value("${mongodb.sockettimeout}")
	private  int SOCKET_TIMEOUT;
	@Value("${mongodb.connecttimeout}")
	private  int CONNECTION_TIMEOUT;
	@Value("${mongodb.socketkeepalive}")
	private  String SOCKET_KEEP_ALIVE;
	
	@SuppressWarnings("deprecation")
	public   DB getDB(String dbName)  {
		 DB conn = null;
		 if(mongoClient == null){
		     intializeMongoClient();
		}
		conn = mongoClient.getDB(dbName);
		return conn;
	}

	public   MongoDatabase getDatabase(String dbName){
		MongoDatabase conn = null;
		if(mongoClient == null){
		     intializeMongoClient();
		}
		conn = mongoClient.getDatabase(dbName);
		return conn;
	}

	public  void intializeMongoClient()  {
		 if (mongoClient == null) {
            MongoClientOptions.Builder buide = new MongoClientOptions.Builder();
            buide.connectionsPerHost(CONNECTIONS_PER_HOST);// 与目标数据库可以建立的最大链接数
            buide.connectTimeout(CONNECTION_TIMEOUT);// 与数据库建立链接的超时时间
            buide.maxWaitTime(MAX_WAIT_TIME);// 一个线程成功获取到一个可用数据库之前的最大等待时间
            buide.threadsAllowedToBlockForConnectionMultiplier(THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER);
            buide.socketTimeout(SOCKET_TIMEOUT);
            if("true".equals(SOCKET_KEEP_ALIVE)) {
            	buide.socketKeepAlive(true);
            }
            // 添加主从配置
            buide.readPreference(ReadPreference.secondaryPreferred());
            MongoClientOptions myOptions = buide.build();
            ServerAddress serverAddress = new ServerAddress(HOST, PORT);
            List<ServerAddress> seeds = new ArrayList<ServerAddress>();
            seeds.add(serverAddress);
            MongoCredential credentials = MongoCredential.createCredential(USERNAME, DBNAME,
                    PASSWORD.toCharArray());
            List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
            credentialsList.add(credentials);
            mongoClient = new MongoClient(seeds, credentialsList,myOptions);
            mongoClient.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT);
	      }
	}

	public   synchronized void closeConnection(){
		if(mongoClient != null){
		    mongoClient.close();
		}
	}
}
